package com.lanou3g.HW_0517.view;

import com.lanou3g.HW_0517.common.Constant;
import com.lanou3g.HW_0517.controller.Controller;
import com.lanou3g.HW_0517.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by dllo on 18/5/16.
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码格式
        request.setCharacterEncoding("utf-8");

        // 获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = controller.login(username, password);

        // 校验
        String msg = "";
        if (user != null) {
            // 登入成功
            // 把用户信息存到session中去
            // 获取session对象

            // 把user 存入session之前,把对象中的密码置空
            user.setPwd("");
            HttpSession session = request.getSession();
            // 把用户信息存到session中
            session.setAttribute(Constant.Session.USER, user);

            //判断登录成功的用户是勾选了七天免登入,七天免登入的值 已经在login.jsp中设置为seven

            String choice = request.getParameter("choice");

            if (choice != null) {
                //获取sessionID,手动设置JSESSION的超时时间,服务器端需要向客户端发送cookie
                //获取sessionID 创建cookie
                String sessionID = session.getId();
                Cookie cookie = new Cookie("JSESSIONID", sessionID);

                //设置cookie有效时间,：如果不设置有效时间，cookie会存储在浏览器的内存中，
                // 浏览器关闭	\cookie信息销毁（会话级别的cookie
                cookie.setMaxAge(7 * 24 * 3600);//一周的超时时间
                session.setMaxInactiveInterval(7 * 24 * 3600);//服务器端session的有效时间

                //设置携带路径，那么该cookie信息会在访问产生该cookie的	web资源所在的路径都携带cookie信息
                cookie.setPath("/");

                //向服务器端发cookie
                response.addCookie(cookie);
            }

            //请求重定向至主页
            response.sendRedirect("/index.jsp");

            // request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "登入");
            request.setAttribute("url", "/login.jsp");
            request.getRequestDispatcher("/msg.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }
}
